package com.leetcode.题库.score1;

import java.util.Arrays;
import java.util.Stack;

/**
 * @BelongsProject: LeetCode
 * @BelongsPackage: com.leetcode.题库.score1
 * @Author: lei
 * @CreateTime: 2024-03-26  13:17
 * @Description:
 * @Version: 1.0
 */
public class 仿LISP运算 {
    public static void main(String[] args) {
        //Scanner scanner = new Scanner(System.in);
        //String s = scanner.nextLine();
        String s = "(sub (mul 2 4) (div 9 3))";
        System.out.println(calculate(s));


    }

    public static String calculate(String expression) {
        Stack<Integer> leftIndex = new Stack<>();
        Stack<Integer> resultStack = new Stack<>();
        int result = 0, right = 0;
        String[] strS = expression.split(" ");
        while (right < strS.length) {
            String str = strS[right];
            String rightStr = String.valueOf(str.charAt(strS[right].length() - 1));
            // 先获取第一个 “)” 的位置
            while (!rightStr.equals(")")) {
                String leftStr = String.valueOf(str.charAt(0));
                if (leftStr.equals("(")) leftIndex.push(right);
                right = right + 1;
                str = strS[right];
                rightStr = String.valueOf(str.charAt(str.length() - 1));
            }
            Integer left = leftIndex.pop();
            String[] resultStr = Arrays.copyOfRange(strS, left, right + 1);
            right = resultCalc(resultStr, resultStack, right);
            right++;
        }
        return "1";

    }

    private static int resultCalc(String[] resultStr, Stack<Integer> resultStack, int resultRight) {
        if (resultStr.length == 3) {
            String s1 = resultStr[0];
            String s2 = resultStr[2];
            int right = s2.length() - 1;
            // 可能出现  ((( 多个左括号的情况
            s1 = s1.substring(1);
            while (s2.charAt(right) == ')') {
                s2 = s2.substring(0, right);
                right--;
            }
            int paramTwo = Integer.parseInt(s2);
            int paramOne = Integer.parseInt(resultStr[1]);
            // 可能出现  ))) 多个右括号的情况
            switch (s1) {
                case "add":
                    resultStack.push(paramOne + paramTwo);
                    break;
                case "sub":
                    resultStack.push(paramOne - paramTwo);
                    break;
                case "mul":
                    resultStack.push(paramOne * paramTwo);
                    break;
                case "div":
                    if (paramTwo == 0)
                        System.out.println("error");
                    else
                        resultStack.push(paramOne / paramTwo);
                    break;
            }
        }
        return resultRight;
    }
}


